package com.java.fileman;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class AuthServlet
 */
public class AuthServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	Logger log;
	private static Properties prop = new Properties();
	private String username;
	private String password;
	private AuthToken authToken;

	public AuthServlet() {
		super();
		// TODO Auto-generated constructor stub
		log = Logger.getLogger(AuthServlet.class);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		String action = (String) request.getParameter("action");
		if (action != null && action.equals("LOGOFF")) {
			HttpSession session = request.getSession();
			session.removeAttribute("authToken");
			getServletConfig().getServletContext()
					.getRequestDispatcher("/login.jsp")
					.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		username = (String) request.getParameter("username");
		password = (String) request.getParameter("password");
		String type = (String) request.getParameter("type");

		log.debug("username=" + username + " password=" + password + " type="
				+ type);

		if ((username == null || username.equals(""))
				|| (password == null || password.equals(""))) {
			request.setAttribute("error", "Username & password required");
			getServletConfig().getServletContext()
					.getRequestDispatcher("/login.jsp")
					.forward(request, response);
			return;
		}

		prop.load(new FileInputStream(getAppDir() + "WEB-INF" + File.separator
				+ "config.properties"));
		if (prop.getProperty("auth.type").equals("basic")) {
			log.debug("Basic authentication type");
			authBasic(request, response);

		} else if (prop.getProperty("auth.type").equals("ldap")) {
			log.debug("LDAP authentication type");
			authLdap(request, response);
		} else if (prop.getProperty("auth.type").equals("both")) {
			log.debug("LDAP/Basic Authentication type");
			
			if (type != null && type.equals("true"))
				authBasic(request, response);
			else
				authLdap(request, response);
			
		} else {
			log.debug("Error in config file for auth.type=?");
			return;
		}

	}

	public String getAppDir() {
		String path = this.getServletContext().getRealPath(File.separator);
		log.debug("Application directory  :  " + path);
		return path;
	}

	public static AuthToken getAuthToken(HttpServletRequest request) {
		HttpSession session = request.getSession();
		return (AuthToken) session.getAttribute("authToken");
	}

	public void authLdap(HttpServletRequest request,
			HttpServletResponse response) {
		log.debug("authLdap()");
		
		try {
			LdapAuth ldap = new LdapAuth(getAppDir());
			authToken = ldap.authenticate(username, password);
			if (authToken != null) {
				log.debug("authToken=" + authToken);
				HttpSession session = request.getSession();
				session.setAttribute("authToken", authToken);
				response.sendRedirect("FileServerServlet");
			} else {
				log.debug("incorrect username or password");
				request.setAttribute("error", "Incorrect username or password");
				getServletConfig().getServletContext()
						.getRequestDispatcher("/login.jsp")
						.forward(request, response);
			}
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void authBasic(HttpServletRequest request,
			HttpServletResponse response) {
		log.debug("authBasic()");
		try {
			BasicAuth basic = new BasicAuth(getAppDir());
			authToken = basic.authenticate(username, password);
			log.debug("authToken = " + authToken == null + " ?");
			if (authToken != null && !authToken.getUsername().equals("")) {
				log.debug("authToken=" + authToken);
				HttpSession session = request.getSession();
				session.setAttribute("authToken", authToken);
				response.sendRedirect("FileServerServlet");
			} else {
				log.debug("incorrect username or password");
				request.setAttribute("error", "Incorrect username or password");
				getServletConfig().getServletContext()
						.getRequestDispatcher("/login.jsp")
						.forward(request, response);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.debug("" + e.getMessage());
			// getServletConfig().getServletContext()
			// .getRequestDispatcher("/login.jsp").forward(request, response);
		} catch (ServletException e) {
			log.debug(e.getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.debug(e.getMessage());
		}
	}
}
